package com.example.myletcodelearing.stack

import com.example.myletcodelearing.fbnq.fbnq

/**
 * @author tgw
 * @date 2022/8/4
 * @describe 栈应用 后缀表达式 计算器计算
 */
class calculatorData {
    val data = Array<String>(10){i -> "" }
    var top = -1

    fun push(inValue:String){
        if (top>=data.size){
            println("越界：$top")
            return
        }
        var value = inValue
        if (top>0){
            println("进入操作符 $top")
            when (value) {
                "+" -> {
                    var index = top-1
                    value = (data[index].toInt()+data[top].toInt()).toString()
                    data[top] = ""
                    top =top -2
                }
                "-" -> {
                    var index = top-1
                    value = (data[index].toInt()-data[ top].toInt()).toString()
                    data[top] = ""
                    top =top -2
                }
                "*" -> {
                    var index = top-1
                    value = (data[index].toInt()*data[top].toInt()).toString()
                    data[top] = ""
                    top =top -2
                }
                "/" -> {
                    var index = top-1
                    value = (data[index].toInt()/data[top].toInt()).toString()
                    data[top] = ""
                    top =top -2
                }
            }
        }

        top++
        data[top] =value

    }

    fun pop():Int{
        if (top==-1){
            println("越界：$top")
            return -1
        }else{
            val value = data[top]
            top--
            return value.toInt()
        }
    }

    fun printValue(){
        var index = top
        while (index>-1){
            println("值：${data[index]}")
            index--
        }
    }
}


fun main(array: Array<String>) {
    println("计算器：后缀表达式")
    val test = calculatorData()
    test.push("9")
    test.push("3")
    test.push("1")
    test.push("-")
    test.push("3")
    test.push("*")
    test.push("+")
    test.push("10")
    test.push("2")
    test.push("/")
    test.push("+")
    test.printValue()
}